package com.trytech.mongoocrawler.common.bean;

import io.netty.channel.socket.nio.NioSocketChannel;
import org.apache.commons.lang3.StringUtils;

import java.util.concurrent.ConcurrentHashMap;

/**
 * @author jiangtao@meituan.com
 * @since: Created on 2018年07月15日
 */
public class ConnectionManager {
    public static ConcurrentHashMap<String, ClientInfo> connectionMap = new ConcurrentHashMap<String, ClientInfo>();

    public static void registerConnection(ClientInfo clientInfo) {
        if (StringUtils.isNotEmpty(clientInfo.getIp())) {
            connectionMap.put(clientInfo.getIp(), clientInfo);
        }
    }

    public static void removeConnection(String clientIp) {
        connectionMap.remove(clientIp);
    }

    public static NioSocketChannel getChannel(String clientIp) {
        ClientInfo clientInfo = connectionMap.get(clientIp);
        if (clientInfo != null) {
            return clientInfo.getSocketChannel();
        }
        return null;
    }

    public static NioSocketChannel getFreeChannel() {
        for (ClientInfo clientInfo : connectionMap.values()) {
            if (clientInfo.getStatusEnum().equalsTo(ClientInfo.ClientStatusEnum.FREE)) {
                return clientInfo.getSocketChannel();
            }
        }
        return null;
    }
}
